<template>
  <div class="loading-container">
    <!-- 显示当前帧图片 -->
    <img :src="curSrc" class="loading-image">
  </div>
</template>
<script setup lang="ts" name="MyLoadingView">
import emitter from '@/main';
import { MyTimerUtils } from '@/utils/my-timer';
import { ref, onMounted, onUnmounted } from 'vue';
//更好的方法是:
//1.<MyLoadingView ref="loadingView" />
//2.const loadingView = ref<InstanceType<typeof MyLoadingView> | null>(null)

//需要传入一个用于emitter订阅的id，然后外部通过，emitter.emit(onId, true)开始和停止动画
// <MyLoadingView onId="loading" />
// <button @click="emitter.emit('loading', true)">开始</button>
// <button @click="emitter.emit('loading', false)">停止</button>
const props = defineProps(['onId'])
const path = '/loading/loading'
const size = 12;
const curSrc = ref('/loading/loading1.png')
const timer = MyTimerUtils.build((i) => {
  curSrc.value = path + (i % size + 1) + '.png'
}, 100)

// 开始播放动画
const startAnimation = () => {
  if (timer.isRunning()) return;
  timer.start()
};

// 停止播放动画
const stopAnimation = () => {
  timer.stop()
};

emitter.on(props.onId,(run)=>{
 if(run){
    startAnimation()
  }else{
    stopAnimation()
  }
})

// 组件挂载时自动播放
onMounted(() => {
  // if (props.autoplay) {
  //   startAnimation();
  // }
});

// 组件卸载时清理资源
onUnmounted(() => {
  stopAnimation();
  emitter.off(props.onId)
});

// 暴露公共方法
defineExpose({
  start: startAnimation,
  stop: stopAnimation,
  isRuning: timer && timer.isRunning(),
});
</script>
<style scoped>
.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
}

.loading-image {
  width: 60px;
  height: 60px;
  animation-timing-function: linear;
}
</style>
